package com.monitor.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.monitor.entity.*;
import com.monitor.service.*;
import com.monitor.util.BlankUtil;
import com.monitor.util.Result;
import com.monitor.util.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 理赔单表 前端控制器
 * </p>
 *
 * @author LX
 * @since 2018-09-25
 */
@RestController
@RequestMapping("/erpClaims")
@Api(description="理赔单表")
public class ErpClaimsController {

    @Resource
    private ErpUserService userService;
    @Resource
    private ErpCustomerService customerService;
    @Resource
    private ErpClaimsService claimsService;
    @Resource
    private ErpSaleRepairGarageService saleRepairGarageService;
    @Resource
    private ErpSaleRepairRepairService saleRepairRepairService;
    @Resource
    private ErpSaleRepairOrderService repairOrderService;
    @Resource
    private ErpSaleRepairSaleService repairSaleService;
    @Resource
    private ErpMaterielFlowMaterielService flowMaterielService;
    @Resource
    private ErpManagementService managementService;
    
    @Value("${web.upload-path}")
    private String path;
    
    @Value("${server.ip}")
	private String serverIp;

    @RequestMapping("/getNumbersBycustId")
    @ApiOperation("销售维修单号查询")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<List<Map<String,Object>>> getClientsById(Integer custId) {
        Result<List<Map<String,Object>>> result=new Result<List<Map<String,Object>>>();
        try{
            List<Map<String,Object>> mapList=new ArrayList<>();
            ErpCustomer customer=customerService.selectById(custId);
            List<ErpCustomer> customers=customerService.selectList(new EntityWrapper<ErpCustomer>().eq("cus_sup_company",customer.getCusCode()).or().eq("cus_service_com",customer.getCusCode()));

            customers.add(customer);
            List<Integer> custIds=customers.stream().map(ErpCustomer::getId).collect(Collectors.toList());
            String custIdsStr= BlankUtil.listToString(custIds);
            List<ErpSaleRepairOrder> saleRepairOrders=repairOrderService.selectList(new EntityWrapper<ErpSaleRepairOrder>().in("customer_id",custIdsStr));
            for (ErpSaleRepairOrder saleRepairOrder:saleRepairOrders) {
                List<ErpSaleRepairRepair> saleRepairRepairs=saleRepairRepairService.selectList(new EntityWrapper<ErpSaleRepairRepair>().eq("order_id",saleRepairOrder.getId()));
                List<ErpSaleRepairGarage> saleRepairGarages=saleRepairGarageService.selectList(new EntityWrapper<ErpSaleRepairGarage>().eq("order_id",saleRepairOrder.getId()));
                List<ErpSaleRepairSale> saleRepairSales=repairSaleService.selectList(new EntityWrapper<ErpSaleRepairSale>().eq("order_id",saleRepairOrder.getId()));
                Map<String,Object> map=new HashMap<String,Object>();
                map.put("saleRepairRepairs",saleRepairRepairs);
                map.put("saleRepairGarages",saleRepairGarages);
                map.put("saleRepairSales",saleRepairSales);
                map.put("saleRepairOrder",saleRepairOrder);
                mapList.add(map);
            }
            result.setCount(1);
            result.setData(mapList);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }

    @RequestMapping("/inertOrUpdateClaims")
    @ApiOperation("添加Or修改理赔单信息")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "String", paramType = "query"),*/
            @ApiImplicitParam(name = "custId", value = "用户ID", required = false, dataType = "String", paramType = "query")
    })
    public @ResponseBody
    Result<Integer> inertOrUpdateCustUser(Integer custId,ErpClaims claims,ErpMaterielFlowMateriel flowMateriel,ErpManagement management) {
        Result<Integer>  result=new Result<Integer>();
        try{
            ErpUser user=userService.selectById(custId);
            ErpCustomer customer=customerService.selectById(user.getCustomerId());
            ErpMaterielFlowMateriel flowMateriel1= flowMaterielService.selectOne(new EntityWrapper<ErpMaterielFlowMateriel>().eq("materiel_name",flowMateriel.getMaterielName()).eq("materiel_brand",flowMateriel.getMaterielBrand()).eq("materiel_Specifications",flowMateriel.getMaterielSpecifications()).eq("materiel_model",flowMateriel.getMaterielModel()).eq("materiel_place",flowMateriel.getMaterielPlace()).eq("materiel_state",flowMateriel.getMaterielState()).eq("materiel_unit",flowMateriel.getMaterielUnit()));

            claims.setMaterielId(flowMateriel1.getId());
            claims.setCreateBy(user.getRealName());

            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(currentTime);
            management.setDt(dateString);
            management.setWorkId(claims.getClaimsId());
            management.setClientName(claims.getCustomerName());
            management.setCarNumber(claims.getCarPalte());
            management.setWorkProject("质量理赔");
            management.setMaintian(claims.getClaimsPrice());
            management.setCustomerId(customerService.selectOne(new EntityWrapper<ErpCustomer>().eq("cus_name",claims.getCustomerName())).getId());
            if(claims.getType()==1){
                management.setCope(claims.getClaimsPrice());
                //此处应该生成收款单
            }
            if(claims.getType()==2){
                management.setAccounts(claims.getClaimsPrice());
                //此处应该生成收款单
            }
            management.setWorkPlace(customer.getCusName());
            managementService.insert(management);

            result.setCount(1);
            result.setData(claimsService.insertOrUpdate(claims)?1:0);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }


    @RequestMapping("/selectClaims")
    @ApiOperation("质量理赔列表查询")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "userId", value = "用户ID", required = false, dataType = "String", paramType = "query"),
    	@ApiImplicitParam(name = "type", value = "1:质量理赔2:物料索赔", required = false, dataType = "int", paramType = "query")
    })
    public Result<List<ErpClaims>> selectClaims(int type,int userId){
    	 ErpCustomer customer=customerService.selectById(userId);
         List<ErpCustomer> customers=customerService.selectList(new EntityWrapper<ErpCustomer>().eq("cus_sup_company",customer.getCusCode()).or().eq("cus_service_com",customer.getCusCode()).orderBy("id", true));
         customers.add(customer);
         List<String> custIds=customers.stream().map(ErpCustomer::getCusName).collect(Collectors.toList());
         String custIdsStr= BlankUtil.listStringToString(custIds);
         Result<List<ErpClaims>> result=claimsService.selectByCustName(type,custIdsStr);
         return result;
    }
    
    @RequestMapping("/addClaims")
    @ApiOperation("添加质量理赔数据")
    public Result<Integer> addClaims(@ModelAttribute ErpClaims claims,Integer custId){
    	return claimsService.addClaims(claims,custId);
    }
    
    @RequestMapping("/selectSaleAndOrderList")
    @ApiOperation("质量理赔添加页面 点击生产编号里的查询按钮")
    @ApiImplicitParams({
         @ApiImplicitParam(name = "word", value = "生产编号", required = false, dataType = "String", paramType = "query"),
         @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "String", paramType = "query")
    })
    public Result<List<Map<String, Object>>> selectSaleAndOrderList(int custId,String word){
    	return claimsService.selectSaleAndOrderList(custId, word);
    }
    
    @RequestMapping("/selectDateilBySrsId")
    @ApiOperation("质量理赔添加页面 点击生产编号里的查询按钮弹出的选择功能")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "srId", value = "销售维修-销售表ID", required = false, dataType = "int", paramType = "query")
    	//@ApiImplicitParam(name = "type", value = "1:质量理赔2:物料索赔", required = false, dataType = "String", paramType = "query")
    })
    public Result<Map<String, Object>> selectDateilBySrsId(int srId){
    	return claimsService.selectDateilBySrsId(srId);
    }
    
    @RequestMapping("/selectByClaimsId")
    @ApiOperation("根据理赔单号查询详情")
    @ApiImplicitParam(name = "claimsId", value = "理赔单号", required = false, dataType = "String", paramType = "query")
    public Result<ErpClaims> selectByClaimsId(String claimsId){
    	try {
			List<ErpClaims> list=claimsService.selectList(new EntityWrapper<ErpClaims>().eq("claims_id", claimsId));
			if(list.size()>0) {
				return new Result<ErpClaims>(list.get(0), 1);
			}else {
				return new Result<ErpClaims>(null, 1);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Result<ErpClaims>(1, e.getMessage());
		}
    }
    
    @RequestMapping("/upload")
    @ApiOperation(value="上传文件", notes="")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file",paramType="query")
	public Map<String, Object> upload(MultipartFile file, HttpServletRequest request) {
		String str = UploadUtil.uploadYa(path, request, file);
		Map<String, Object> map = new HashMap<>();
		map.put("code", 0);
		map.put("msg", "成功");
		Map<String, Object> map1 = new HashMap<>();
		map1.put("src", serverIp + str);
		map.put("data", map1);
		return map;
	}
    
    @RequestMapping("/selectSaleAndOrderListByCarPlate")
    @ApiOperation("物料索赔添加页面 点击生产编号里的查询按钮")
    @ApiImplicitParams({
         @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "String", paramType = "query"),
         @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "String", paramType = "query")
    })
    public Result<List<Map<String, Object>>> selectSaleAndOrderListByCarPlate(int custId,String word){
    	return claimsService.selectSaleAndOrderListByCarPlate(custId, word);
    }
}

